global class AccountSysUtil {


	//global static String  addCustbaseUrl = 'https://esb.maccura.com:9088/api/Domain/univer/mkaddCustbase/addCustbase';
	//global static String  addMedCustDocUrl = 'https://esb.maccura.com:9088/api/Domain/univer/mkaddMedCustDoc/addMedCustDoc';

	///所属地区处理规则
	// 国内客户: 地级市   国外客户 : 国家 

	///同步医药档案(集团器械客商管理档案)
	WebService static String addMedCustDoc(String nccid){
		
		String url = Label.addMedCustDocUrl;//'https://esb.maccura.com:9088/api/Domain/univer/mkaddMedCustDoc/addMedCustDoc';
		 // 获取nc准入
       	NCCustomer__c nccus = getNCCustomer(nccid);

       	if(nccus.isSycCustMed__c  == true) return '已经同步,请不要重复点击!';
       	if(nccus.isSycCustbase__c  != true) return '请先同步集团档案!';
       	if(nccus.ApprovalStatus__c != '审批通过' ) return '未审批通过不能同步!';
       	Map<String,Object> data = new Map<String,Object>();

       	List<Object> meds = new List<Object>();
       	Map<String,String> med = new Map<String,String>();
		User u = [select Name ,ExuserCode__c from User where Id =: UserInfo.getUserId()];


       	//custcode 客户编码
       	med.put('custcode', nccus.Customer__r.AccountNumber );
       	//vcorpname 企业名称(中文)
       	med.put('vcorpname', nccus.Customer__r.Name );
       	//vcorpenglish 企业名称 英文
       	//vcorpph 企业名称 拼音
       	//vshortname 企业简称 中文
       	//vshortenglish 企业简称 英文
       	//vshortph 企业简称 拼音
       	//vregcountryname 注册国家 中文
       	 med.put('vregcountryname',nccus.Customer__r.Country__r.Name  );
       	//vregcountryenglish 注册国家 英文
       	//vregcountryph 注册国家 拼音
       	//vcorpclassname 企业类别
       	 med.put('vcorpclassname', nccus.CusType__c );

       	//custflagname 经营类型
       	 med.put('custflagname', '客户' );
       	//areaclname 所属地区

       	 med.put('areaclname', nccus.Customer__r.RecordType.DeveloperName.toLowercase().contains('abroad')  ?  nccus.Customer__r.Country__r.Name  :nccus.Customer__r.City__r.Name );
       	//dlicencedate 许可证有效期
       	if(nccus.TermValidity__c != null ) med.put('dlicencedate', Datetime.newInstance(nccus.TermValidity__c.year(), nccus.TermValidity__c.month() , nccus.TermValidity__c.day()).format('yyyy-MM-dd'));
       	//vlicence 许可证号
       	 med.put('vlicence', nccus.MedicalNo__c  );

       	//vbusinessdate 营业执照有效期至
       	if(nccus.ValidityBusinessLicense__c != null ) med.put('vbusinessdate', Datetime.newInstance(nccus.ValidityBusinessLicense__c.year(), nccus.ValidityBusinessLicense__c.month() , nccus.ValidityBusinessLicense__c.day()).format('yyyy-MM-dd'));
       	//vbusinesscerti 营业执照号
       	med.put('vbusinesscerti',nccus.BusinessLicense__c);
       	//qualitysys 质量认证体系 QualitySystem__c
       	med.put('qualitysys',nccus.QualitySystem__c);
       	//dqualitydate 质量认证体系有效期 ValidityQualitySystem__c
       	if(nccus.ValidityQualitySystem__c != null ) med.put('dqualitydate', Datetime.newInstance(nccus.ValidityQualitySystem__c.year(), nccus.ValidityQualitySystem__c.month() , nccus.ValidityQualitySystem__c.day()).format('yyyy-MM-dd'));
       	//byearcheck 营业执照是否年检

       	//ishospital 是否医院
       	//ispayoffhos 是否盈利性医院
       	//istrusteeshiphos 是否托管药房医院
       	//icommshospital 是否公立医院
       	//isdesignate 是否社保定点
       	//iscothospital 是否定点医疗机构 
       	//isleechdom 是否药店
       	//isotc 是否OTC药店
       	//iscatenation 是否连锁店
       	//ismiddle 是不居间人
       	//vidcard 身份证号(居间人专用)
       	//finvoicetype 发票类型
       	med.put('finvoicetype',nccus.InvoiceType__c);
       	//iinvoicelimit 发票限额
       	
       	med.put('iinvoicelimit',nccus.LnvoiceLimit__c);
       	//iinvoicerequire 发票要求
       	med.put('iinvoicerequire',nccus.InvoiceRequirement__c);
       	//ccorpid 企业编号 
       	//ismedspecciality 是否启用医药特性
       	//vremark 备注
       	//daddarchidate 建档日期
       	//backfillflag 是否回写客商基本档案
       	med.put('backfillflag','Y');
       	//accountcreater 创建人
       	//accountupdater 修改人
       	//创建人  accountcreater 操作类为1时，必输项
		med.put('accountcreater',u.Name);
		//修改人  accountupdater 操作类不为1时，必输项
		med.put('accountupdater',u.Name);
		//操作类型 opertype 必要项 1=新增  2=修改  
		med.put('opertype','1');
       	//pk_meddoc 医药属性pk 
       	//medid 来源id 
		med.put('medid',nccus.id);

       	//custprop 客商类型 经销商 0 终端 1 供应商 4
		med.put('custprop',nccus.Customer__r.RecordType.DeveloperName.contains('dealer') ? '0' : '1'  );
       	//pk_relacubasdoc 客商基本档案pk 
		med.put('pk_relacubasdoc',nccus.Customer__r.NCICCode__c  );

		meds.add(med);
		Map<String,Object> d = new Map<String,Object>();
		d.put('data', meds);

		System.debug(JSON.serialize(d));

		 HttpRequest req = new HttpRequest();
          req.setBody(JSON.serialize(d));
          req.setMethod('POST');
          req.setHeader('Content-Type','text/plain');
          req.setEndpoint(url);
          HttpResponse res = Utils.postRequest(req, 2);
          System.debug(res.getBody());
            Map<String,Object> r = null;
                //如果是测试
          if(Test.isRunningTest()){
            Map<String,Object>  resBody= new Map<String,Object>();
            resBody.put('code','0');
            resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"custcode\":\"111\",\"invcode\":\"xx001\",\"vbatchcode\":\"001234\"}]}');
              r =  resBody;
          }else{
            r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
          }
          /*
				{"result":"{\"result_msg\":\"操作成功\",\"result\":1,\"data\":\"0001AA10000000CAGAZF\"}","code":"0","msg":"success"}
          	{"result":"{\"result_msg\":\"[UC000-0001587]不能重复\",\"result\":0}","code":"0","msg":"success"}
          */
          	if(r.get('code') == 0 || r.get('code') == '0'){

                 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                  if( rs.get('result') == 1 ){
                  		try {
	                  		nccus.isSycCustMed__c = true ;
                  			update nccus ; 
                  		
	                  		return '同步成功!';
                  		}
                  		catch (Exception e) {
                  		    
                  		    return '同步成功!回写数据失败!'+e.getMessage();
                  		}
                  		
                  	    
                  }else{
                  		return '同步失败:'+String.valueOf(rs.get('result_msg'));
                  }
              }else{

              	return '同步失败:'+String.valueOf(r.get('msg'));
              }


	}

	//查找 nc 空闲客户编码
	global static String getLasetAccountNumber(String acctype ){

		String sql = 'select  maxcode from v_xlh_custcode_max  where custtype = \''+acctype+'\'';
		sql = '{data:"'+sql+'"}';
		//String url = Label.queryDataForTest;//测试
		String url = Label.queryResposityURL;//正式
		 HttpRequest req = new HttpRequest();
              req.setBody(sql);
              req.setMethod('POST');
              req.setHeader('Content-Type','text/plain');
              req.setEndpoint(url);
              HttpResponse res = Utils.postRequest(req, 2);
              System.debug(res.getBody());
                Map<String,Object> r = null;
                    //如果是测试
              if(Test.isRunningTest()){
                Map<String,Object>  resBody= new Map<String,Object>();
                resBody.put('code','0');
                resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"maxcode\":\"6666\",\"invcode\":\"xx001\",\"vbatchcode\":\"001234\"}]}');
                  r =  resBody;
              }else{
                r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
              }
              if(r.get('code') == 0 || r.get('code') == '0'){

                 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                  if( rs.get('result') == 1 ){
                  		List<Object> datas = (List<Object>)rs.get('data');
                  		if(datas.size() == 0 ) return 'error';
                  		Map<String,Object> mo = (Map<String,Object>)datas.get(0);
                  	  return String.valueOf(mo.get('maxcode'));
                  }
              }
              return 'error';
		

	}
	global static NCCustomer__c getNCCustomer(String nccid){
		 Schema.DescribeSobjectResult m = NCCustomer__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;

        sql += ' ,Customer__r.City__r.Name, Customer__r.Name,Customer__r.Country__r.Name , Customer__r.NCICCode__c, Customer__r.RecordType.DeveloperName ,Customer__r.AccountNumber ,Customer__r.AccName__c from NCCustomer__c where Id = \'' + nccid + '\'';

       return Database.query(sql);
	}
	///NC准入申请 同步客户基本档案
	WebService static String addCustbase(String nccid  ){


		String url = Label.addCustbaseUrl;//'https://esb.maccura.com:9088/api/Domain/univer/mkaddCustbase/addCustbase';
		User u = [select Name ,ExuserCode__c from User where Id =: UserInfo.getUserId()];
		///1.检查是否存在 
			//客户编码: 
			//客户名称: 

		 // 获取nc准入
       	NCCustomer__c nccus = getNCCustomer(nccid);
       	if(nccus.isSycCustbase__c  == true) return '已经同步,请不要重复点击!';
       	if(nccus.ApprovalStatus__c != '审批通过' ) return '未审批通过不能同步!';

        String custcode = getLasetAccountNumber(nccus.Customer__r.RecordType.DeveloperName.toLowercase().contains('dealer') ?'3':'6');
        if(custcode == 'error') return '获取NC客户编码失败,请重试!';
        //custcode= '113455tt';
		/// 组装数据
		Map<String,Object> data = new Map<String,Object>();
		//基本档案
		Map<String,String> custbasevo = new Map<String,String>();
		//客户档案PK pk_custdoc
		custbasevo.put('custcode', custcode  );//客户编码 
		custbasevo.put('custname', nccus.Customer__r.Name);//客户名

		custbasevo.put('custshortname', nccus.Customer__r.AccName__c);//客户简称
		//外文名称 engname
		//助记码 mnecode
		//所属行业 tradename
		//是否散户 freecustflag Y/N
		//是否DRP结点 drpnodeflag Y/N
		//是否渠道集成  isconnflag Y/N
		//客商总公司编码  pk_cubasdoc1 
		//客商类型  custprop_name 外部单位：0  内部核算单位：1 内部法人单位：2 内部渠道成员：3
		custbasevo.put('custprop_name','外部单位');
		//所属地区名称  areaclname //地区分类名称
		//if( String.isBlank(nccus.RegionOrigin__c ) == false )custbasevo.put('areaclname',nccus.RegionOrigin__c );
       	 custbasevo.put('areaclname', nccus.Customer__r.RecordType.DeveloperName.toLowercase().contains('abroad')  ?  nccus.Customer__r.Country__r.Name  :nccus.Customer__r.City__r.Name );
		//纳税人登记号 taxpayerid 
		if( String.isBlank(nccus.DutyParagraph__c ) == false )custbasevo.put('taxpayerid',nccus.DutyParagraph__c );

		//法人 legalbody 
		if( String.isBlank(nccus.legalPerson__c ) == false )custbasevo.put('legalbody',nccus.legalPerson__c );

		//经济类型 ecotypesincevfivename 
		//注册资金  registerfund 
		if( nccus.AmountRegisteredCapital__c != null  )custbasevo.put('registerfund',String.valueOf(nccus.AmountRegisteredCapital__c ));

		//备注  memo
		//价格分组 pricegroupname 
		//经营方式 jyfs  01,02,03,04
		if( String.isBlank(nccus.OperationMode__c ) == false )custbasevo.put('jyfs',nccus.OperationMode__c );

		//终端类型 def20 经销商 0 终端 1 供应商 4
		//zdlx
		custbasevo.put('zdlx',nccus.Customer__r.RecordType.DeveloperName.toLowercase().contains('dealer') ? '经销商' : '终端'  );

 		//医院性质  yyxz 
 		//体外诊断类别 twzd  
 		//医疗器械经营到期时间 def4 
 		//医疗器械经营到期范围 def5 
 		//药品经营范围 def6 
 		//开票合并方式 def7 
		//对方机构编码 def8
		//组织机构代码证到期时间 def9 
		//税务登记到期时间 def10 
		//经济性质 jjxz 01-08
		if( String.isBlank(nccus.UnitProperty__c ) == false )custbasevo.put('jjxz',nccus.UnitProperty__c );

		//通信地址 conaddr
		if( String.isBlank(nccus.SPaddress__c ) == false )custbasevo.put('conaddr',nccus.SPaddress__c );

		//邮政编码  zipcode 
		//电话1 phone1 
		if( String.isBlank(nccus.Telephone__c ) == false )custbasevo.put('phone1',nccus.Telephone__c );

		//电话2 phone2 
		//电话3 phone3 
		//传真1 fax1 
		//传真2 fax2
		//联系人1 linkman1 
		if( String.isBlank(nccus.Contacts__c ) == false )custbasevo.put('linkman1',nccus.Contacts__c );

		//联系人2 linkman2
		//联系人3 linkman3
		//呼机1 bp1 
		//呼机2 bp2 
		//呼机3 bp3
		//网址 url 
		//创建人  accountcreater 操作类为1时，必输项
		custbasevo.put('accountcreater',u.Name);
		//修改人  accountupdater 操作类不为1时，必输项
		custbasevo.put('accountupdater',u.Name);
		//操作类型 opertype 必要项 1=新增  2=修改  
		custbasevo.put('opertype','1');

		//是否需要回写医药档案 relacubasdoc 1=回写 2=不回写
		custbasevo.put('relacubasdoc','2');
		//custbasevo.put('def11','Y');



		//地址
		List<Object> adderVOs = new List<Object>();
		if(nccus.ReceiptAddress__c != null ){
			Map<String,String >adderVO = new Map<String,String>();
		
			//发货地址名称 addrname
			
			adderVO.put('addrname',nccus.ReceiptAddress__c);
			//发货地址PK pk_custaddr 操作类不为1时，必输项
			//电话 addrphone 
			
			adderVO.put('addrphone',nccus.ReceivingPhone__c);
			//联系人 addrlinkman 
			
			adderVO.put('addrlinkman',nccus.Consignee__c);
			//是否默认地址 mobilephone1  ???? 
			adderVO.put('mobilephone1','Y');

			//所属地区 areaclname
			//adderVO.put('areaclname','国内');
       		 adderVO.put('areaclname', nccus.Customer__r.RecordType.DeveloperName.toLowercase().contains('abroad')  ?  nccus.Customer__r.Country__r.Name  :nccus.Customer__r.City__r.Name );

			//地点 addressname
			//客商编码 custcode
			adderVO.put('custcode', custcode);
			//操作类型 opertype
			adderVO.put('opertype','1');
			//来源id aid  1=新增  2=修改 
			adderVO.put('aid',nccus.id );
			adderVOs.add(adderVO);
		}
		

		//银行
		List<Object> bankerVOs = new List<Object>();
		Map<String,String> bankerVO = new Map<String,String>();
		if(nccus.BankAccount__c!= null ){
			//银行信息PK pk_bankaccbas 操作类不为1时，必输项
			//开户银行PK pk_custbank
			//账号 account
			bankerVO.put('account', nccus.BankAccount__c);
			//账户名称 accountname
			bankerVO.put('accountname', String.valueOf(nccus.AccountName__c));

			//账户编码 accountcode 
			bankerVO.put('accountcode', nccus.BankAccount__c);

			//助记码 remcode 

			//开户银行  accname
			
			bankerVO.put('accname',nccus.DepositBank__c);
			//银行类别 banktypename
			bankerVO.put('banktypename',nccus.BankName__c);
			//币种名称 currtypename
			//账户性质 accountproperty 单位：0 个人：1
	 		//开户日期 accopendate 
	 		//联系人  contactpsn 
	 		//联系电话 tel 
	 		//账户状态  accstate 
	 		//封存日期  frozendate 
	 		//是否默认 defflag Y/N
			bankerVO.put('defflag', 'Y');
	 		//备注 mome 
	 		//网银开通状态  netqueryflag 
	 		//网银接口类别 netbankinftpname 
	 		//单位名称 unitname 
	 		//联行号   combineaccnum 
	 		//地区代码 areacode 
	 		//开户地区  bankarea 
	 		//机构号  orgnumber 
	 		//省份 province
	 		//集团号 groupid 
	 		//城市 city
	 		//客户编码 custcode 
			bankerVO.put('custcode', custcode);
	 		//是否签约 signflag Y/N 
	 		//操作类型 opertype 1=新增  2=修改 
			bankerVO.put('opertype','1');
	 		//创建人  accountcreater 操作类为1时，必输项
	 		bankerVO.put('accountcreater',u.Name);
			//修改人  accountupdater 操作类不为1时，必输项
			bankerVO.put('accountupdater',u.Name);
			//来源id aid  
			bankerVO.put('bid',nccus.id);
			bankerVOs.add(bankerVO);

		}
		data.put('custbasevo', custbasevo);
		data.put('adderVOs',adderVOs);
		data.put('bankerVOs',bankerVOs);
		List<Object> datas = new List<Object>();
		datas.add(data);
		Map<String,Object> d = new Map<String,Object>();
		d.put('data', datas);

		System.debug(JSON.serialize(d));
		 HttpRequest req = new HttpRequest();
          req.setBody(JSON.serialize(d));
          req.setMethod('POST');
          req.setHeader('Content-Type','text/plain');
          req.setEndpoint(url);
          HttpResponse res = Utils.postRequest(req, 2);
          System.debug(res.getBody());
            Map<String,Object> r = null;
                //如果是测试
            /*
				{"result":"{\"result_msg\":\"操作成功\",\"result\":1,\"data\":
				{\"pk_custdoc\":\"0001AA10000000CAGFM1\",\"adderVOs\":[{\"pk_custaddr\":\"0001AA10000000CAGFM2\",\"aid\":\"a0i0k000000EeetAAC  \"}],\"bankerVOs\":[{\"bid\":null,\"pk_custbank\":null,\"pk_bankaccbas\":null}]}}","code":"0","msg":"success"}
            */

          if(Test.isRunningTest()){
            Map<String,Object>  resBody= new Map<String,Object>();
            resBody.put('code','0');
            resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":{\"custcode\":\"111\",\"pk_custdoc\":\"xx001\",\"vbatchcode\":\"001234\"}}');
              r =  resBody;

          }else{
            r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
          }

             if(r.get('code') == 0 || r.get('code') == '0'){

                 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                  if( rs.get('result') == 1 ){
                  		Map<String,Object> result  = (Map<String,Object> )rs.get('data');
                  		System.debug('AccountSysUtil==>'+result);
                  		try {
	                  		nccus.isSycCustbase__c = true ;
                  			update nccus ; 
                  		   Account acc = new Account(Id=nccus.Customer__c ,AccountNumber = custcode, NCICCode__c =String.valueOf(result.get('pk_custdoc')));
	                  		
	                  		update acc ; 
	                  		return '同步成功!';
                  		}
                  		catch (Exception e) {
                  		    
                  		    return '同步成功!回写数据失败!'+e.getMessage();
                  		}
                  		
                  	    
                  }else{
                  		return '同步失败:'+String.valueOf(rs.get('result_msg'))+custcode;
                  }
              }else{

              	return '同步失败:'+String.valueOf(r.get('msg'))+custcode;
              }

          
          return '异常失败!';
          



	}



	///经销商主要用户 同步客户基本档案
	WebService static String majorAddCustbase(String mid  ){


		String url = Label.addCustbaseUrl; //'https://esb.maccura.com:9088/api/Domain/univer/mkaddCustbase/addCustbase';
		User u = [select Name ,ExuserCode__c from User where Id =: UserInfo.getUserId()];
		///1.检查是否存在 
			//客户编码: 
			//客户名称: 

		 // 获取nc准入
		MajorUserInfo__c major = [select Id,IsSycToNc__c,MajorCustomer__c,MajorCustomer__r.Name,MajorCustomer__r.City__r.Name ,
		MajorCustomer__r.AccName__c,MajorCustomer__r.RecordType.DeveloperName,MajorCustomer__r.Country__r.Name,MajorCustomer__r.NCICCode__c
		 from MajorUserInfo__c where Id=: mid ];
       //	NCCustomer__c nccus = getNCCustomer(nccid);
		 if(major.MajorCustomer__r.NCICCode__c != null ) return '已经存在NC客户,无须同步!';
       	if(major.IsSycToNc__c  == true) return '已经同步,请不要重复点击!';

        String custcode = getLasetAccountNumber('6');
        if(custcode == 'error') return '获取NC客户编码失败,请重试!';
        //custcode= '113455tt';
		/// 组装数据
		Map<String,Object> data = new Map<String,Object>();
		//基本档案
		Map<String,String> custbasevo = new Map<String,String>();
		//客户档案PK pk_custdoc
		custbasevo.put('custcode', custcode  );//客户编码 
		custbasevo.put('custname', major.MajorCustomer__r.Name);//客户名

		custbasevo.put('custshortname', major.MajorCustomer__r.AccName__c);//客户简称
		//外文名称 engname
		//助记码 mnecode
		//所属行业 tradename
		//是否散户 freecustflag Y/N
		//是否DRP结点 drpnodeflag Y/N
		//是否渠道集成  isconnflag Y/N
		//客商总公司编码  pk_cubasdoc1 
		//客商类型  custprop_name 外部单位：0  内部核算单位：1 内部法人单位：2 内部渠道成员：3
		custbasevo.put('custprop_name','外部单位');
		//所属地区名称  areaclname //地区分类名称
		//if( String.isBlank(nccus.RegionOrigin__c ) == false )custbasevo.put('areaclname',nccus.RegionOrigin__c );
       	 custbasevo.put('areaclname', major.MajorCustomer__r.RecordType.DeveloperName.toLowercase().contains('abroad')  ?  major.MajorCustomer__r.Country__r.Name  :major.MajorCustomer__r.City__r.Name );
		//纳税人登记号 taxpayerid 
		//if( String.isBlank(nccus.DutyParagraph__c ) == false )custbasevo.put('taxpayerid',nccus.DutyParagraph__c );

		//法人 legalbody 
		//if( String.isBlank(nccus.legalPerson__c ) == false )custbasevo.put('legalbody',nccus.legalPerson__c );

		//经济类型 ecotypesincevfivename 
		//注册资金  registerfund 
		//if( nccus.AmountRegisteredCapital__c != null  )custbasevo.put('registerfund',String.valueOf(nccus.AmountRegisteredCapital__c ));

		//备注  memo
		//价格分组 pricegroupname 
		//经营方式 jyfs  01,02,03,04
		//if( String.isBlank(nccus.OperationMode__c ) == false )custbasevo.put('jyfs',nccus.OperationMode__c );

		//终端类型 def20 经销商 0 终端 1 供应商 4
		//custbasevo.put('def20', '1'  );
		custbasevo.put('zdlx', '终端');

 		//医院性质  yyxz 
 		//体外诊断类别 twzd  
 		//医疗器械经营到期时间 def4 
 		//医疗器械经营到期范围 def5 
 		//药品经营范围 def6 
 		//开票合并方式 def7 
		//对方机构编码 def8
		//组织机构代码证到期时间 def9 
		//税务登记到期时间 def10 
		//经济性质 jjxz 01-08
		//if( String.isBlank(nccus.UnitProperty__c ) == false )custbasevo.put('jjxz',nccus.UnitProperty__c );

		//通信地址 conaddr
		//if( String.isBlank(nccus.SPaddress__c ) == false )custbasevo.put('conaddr',nccus.SPaddress__c );

		//邮政编码  zipcode 
		//电话1 phone1 
		//if( String.isBlank(nccus.Telephone__c ) == false )custbasevo.put('phone1',nccus.Telephone__c );

		//电话2 phone2 
		//电话3 phone3 
		//传真1 fax1 
		//传真2 fax2
		//联系人1 linkman1 
		//if( String.isBlank(nccus.Contacts__c ) == false )custbasevo.put('linkman1',nccus.Contacts__c );

		//联系人2 linkman2
		//联系人3 linkman3
		//呼机1 bp1 
		//呼机2 bp2 
		//呼机3 bp3
		//网址 url 
		//创建人  accountcreater 操作类为1时，必输项
		custbasevo.put('accountcreater',u.Name);
		//修改人  accountupdater 操作类不为1时，必输项
		custbasevo.put('accountupdater',u.Name);
		//操作类型 opertype 必要项 1=新增  2=修改  
		custbasevo.put('opertype','1');

		//是否需要回写医药档案 relacubasdoc 1=回写 2=不回写
		custbasevo.put('relacubasdoc','2');
		//custbasevo.put('def11','Y');



		//地址
		List<Object> adderVOs = new List<Object>();
			Map<String,String >adderVO = new Map<String,String>();
		
			//发货地址名称 addrname
			
			adderVO.put('addrname','SF默认地址');
			//发货地址PK pk_custaddr 操作类不为1时，必输项
			//电话 addrphone 
			
			/*adderVO.put('addrphone','SF默认');
			//联系人 addrlinkman 
			
			adderVO.put('addrlinkman',nccus.Consignee__c);
			//是否默认地址 mobilephone1  ???? 
			adderVO.put('mobilephone1','Y');
*/
			//所属地区 areaclname
			//adderVO.put('areaclname','国内');
			adderVO.put('mobilephone1','Y');
       		 adderVO.put('areaclname', major.MajorCustomer__r.RecordType.DeveloperName.toLowercase().contains('abroad')  ?  major.MajorCustomer__r.Country__r.Name  :major.MajorCustomer__r.City__r.Name );
			
			//地点 addressname
			//客商编码 custcode
			adderVO.put('custcode', custcode);
			//操作类型 opertype
			adderVO.put('opertype','1');
			//来源id aid  1=新增  2=修改 
			adderVO.put('aid',major.id );
			adderVOs.add(adderVO);
		
		

		//银行
		List<Object> bankerVOs = new List<Object>();
		/*Map<String,String> bankerVO = new Map<String,String>();
		if(String.valueOf(nccus.BankAccount__c) != null ){
			//银行信息PK pk_bankaccbas 操作类不为1时，必输项
			//开户银行PK pk_custbank
			//账号 account
			bankerVO.put('account', String.valueOf(nccus.BankAccount__c));
			//账户名称 accountname
			bankerVO.put('accountname', String.valueOf(nccus.AccountName__c));

			//账户编码 accountcode 
			bankerVO.put('accountcode', String.valueOf(nccus.BankAccount__c));

			//助记码 remcode 

			//开户银行  accname
			
			bankerVO.put('accname',nccus.DepositBank__c);
			//银行类别 banktypename
			bankerVO.put('banktypename',nccus.BankName__c);
			//币种名称 currtypename
			//账户性质 accountproperty 单位：0 个人：1
	 		//开户日期 accopendate 
	 		//联系人  contactpsn 
	 		//联系电话 tel 
	 		//账户状态  accstate 
	 		//封存日期  frozendate 
	 		//是否默认 defflag Y/N
			bankerVO.put('defflag', 'Y');
	 		//备注 mome 
	 		//网银开通状态  netqueryflag 
	 		//网银接口类别 netbankinftpname 
	 		//单位名称 unitname 
	 		//联行号   combineaccnum 
	 		//地区代码 areacode 
	 		//开户地区  bankarea 
	 		//机构号  orgnumber 
	 		//省份 province
	 		//集团号 groupid 
	 		//城市 city
	 		//客户编码 custcode 
			bankerVO.put('custcode', custcode);
	 		//是否签约 signflag Y/N 
	 		//操作类型 opertype 1=新增  2=修改 
			bankerVO.put('opertype','1');
	 		//创建人  accountcreater 操作类为1时，必输项
	 		bankerVO.put('accountcreater',u.Name);
			//修改人  accountupdater 操作类不为1时，必输项
			bankerVO.put('accountupdater',u.Name);
			//来源id aid  
			bankerVO.put('bid',nccus.id);
			bankerVOs.add(bankerVO);

		}*/
		data.put('custbasevo', custbasevo);
		data.put('adderVOs',adderVOs);
		data.put('bankerVOs',bankerVOs);
		List<Object> datas = new List<Object>();
		datas.add(data);
		Map<String,Object> d = new Map<String,Object>();
		d.put('data', datas);

		System.debug(JSON.serialize(d));
		 HttpRequest req = new HttpRequest();
          req.setBody(JSON.serialize(d));
          req.setMethod('POST');
          req.setHeader('Content-Type','text/plain');
          req.setEndpoint(url);
          HttpResponse res = Utils.postRequest(req, 2);
          System.debug(res.getBody());
            Map<String,Object> r = null;
                //如果是测试
            /*
				{"result":"{\"result_msg\":\"操作成功\",\"result\":1,\"data\":
				{\"pk_custdoc\":\"0001AA10000000CAGFM1\",\"adderVOs\":[{\"pk_custaddr\":\"0001AA10000000CAGFM2\",\"aid\":\"a0i0k000000EeetAAC  \"}],\"bankerVOs\":[{\"bid\":null,\"pk_custbank\":null,\"pk_bankaccbas\":null}]}}","code":"0","msg":"success"}
            */
				
          if(Test.isRunningTest()){
            Map<String,Object>  resBody= new Map<String,Object>();
            resBody.put('code','0');
            resBody.put('result','{\"result_msg\":\"查询成功！\",\"result\":1,\"data\":[{\"custcode\":\"111\",\"invcode\":\"xx001\",\"vbatchcode\":\"001234\"}]}');
              r =  resBody;

          }else{
            r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());

             if(r.get('code') == 0 || r.get('code') == '0'){

                 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
                  if( rs.get('result') == 1 ){
                  		Map<String,Object> result  = (Map<String,Object> )rs.get('data');
                  		try {
	                  		major.IsSycToNc__c = true ;
	                  		major.NCTime__c	 = System.now();
                  			update major ; 
                  		   Account acc = new Account(Id=major.MajorCustomer__c ,AccountNumber = custcode, NCICCode__c =String.valueOf(result.get('pk_custdoc')));
	                  		
	                  		update acc ; 
	                  		return '同步成功!';
                  		}
                  		catch (Exception e) {
                  		    
                  		    return '同步成功!回写数据失败!'+e.getMessage();
                  		}
                  		
                  	    
                  }else{
                  		return '同步失败:'+String.valueOf(rs.get('result_msg'))+custcode;
                  }
              }else{

              	return '同步失败:'+String.valueOf(r.get('msg'))+custcode;
              }

          }
          return '异常失败!';
          



	}
    
}